﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace User_manage
{
    public partial class User_Lgon : UserControl
    {
        public static bool logstate = false;
        public static H_Level User_Level;
        public static string  User_LevelStr;

        User_manageForm _User_manageForm = new User_manageForm();


        public delegate void end_Click(object sender);
        public event end_Click _endClick;

        public delegate void logoff_Click(object sender);
        public event logoff_Click _logoff_Click;

        public User_Lgon()
        {
            InitializeComponent();

            DataTable buf = Deserialize<DataTable>(Application.StartupPath + "\\Config\\UserInfo.config");
            if (buf != null)
            {
                Text_user.Items.Clear();
                for (int i = 0; i < buf.Rows.Count; i++)
                {
                    string str = buf.Rows[i][0].ToString();
                    Text_user.Items.Add(str);
                }
            }
        }

        private void User_Lgon_Load(object sender, EventArgs e)
        {
            ;
        }

        private void Text_pass_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                uiButton1_Click(null, e);
            }
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {

            if(Text_user.Text=="")
            {
                MessageBox.Show("用户不能为空，请输入！", "Err提示！"); //Text_user
                return;
            }
            if (Text_pass.Text == "")
            {
                MessageBox.Show("密码不能为空，请输入！", "Err提示！");
                return;
            }

            //判断密码是否正确
            DataTable buf = Deserialize<DataTable>(Application.StartupPath + "\\Config\\UserInfo.config");
            if (buf != null)
            {
                DataRow[] drs = buf.Select("用户='" + Text_user.Text + "'");
                string bufPass = "";
                if (drs.Length > 0 && drs[0] != null)
                {
                    bufPass = drs[0]["密码"].ToString();
                }
                else 
                {
                    MessageBox.Show("用户不存在，请重新输入！", "Err提示！");
                }

                string bufdtr = Sha1Sign(Text_pass.Text, Encoding.UTF8);
                StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                if (comparer.Compare(bufPass, bufdtr)==0)
                {
                    string h_level = drs[0]["权限"].ToString();
                    User_Level = H_Level.None;
                    User_LevelStr = "";
                    switch (h_level)
                    {
                        case "厂商": User_Level = H_Level.厂商; User_LevelStr = "厂商"; break;
                        case "管理员": User_Level = H_Level.管理员; User_LevelStr = "管理员"; break;
                        case "生产员": User_Level = H_Level.生产员; User_LevelStr = "生产员"; break;
                        case "班组长": User_Level = H_Level.班组长; User_LevelStr = "班组长"; break;
                    }

                    if (logstate)
                    {
                        Text_pass.Text = "";
                        this._endClick?.Invoke(this);
                    }
                    else
                    {
                        MessageBox.Show(User_LevelStr + " 登录成功！", "提示！");
                    }
                    
                }
                else
                {
                    MessageBox.Show("密码不正确，请重新输入！", "Err提示！");
                    Text_pass.Text = "";
                }
            }
            else
            {
                MessageBox.Show("密码文件丢失，请重新添加用户！", "Err提示！");
            }
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            Text_user.Text = "";
            Text_pass.Text = "";
            User_LevelStr = "";
            User_Level = H_Level.None;
            this._logoff_Click?.Invoke(this);
            //if (MessageBox.Show("是否要退出/注销登录！", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            //{
            //    Text_user.Text = "";
            //    Text_pass.Text = "";
            //    User_LevelStr = "";
            //    User_Level = H_Level.None;
            //}
        }

        private void uiImageButton1_Click(object sender, EventArgs e)
        {
            if(User_Level == H_Level.管理员)
            {
                _User_manageForm.ShowDialog(this);
                ;

                DataTable buf = Deserialize<DataTable>(Application.StartupPath + "\\Config\\UserInfo.config");
                if (buf != null)
                {
                    Text_user.Items.Clear();
                    for (int i = 0; i < buf.Rows.Count; i++)
                    {
                        string str = buf.Rows[i][0].ToString();
                        Text_user.Items.Add(str);
                    }
                }
            }
            else
            {
                MessageBox.Show("错误！您不是管理员/或未登录！", "Err提示！");
            }
           
        }

        /// SHA1加密
        /// </summary>
        /// <param name="content">待加密的字符串</param>
        /// <param name="encode">编码方式</param>
        /// <returns></returns>
        public string Sha1Sign(string content, Encoding encode)
        {
            try
            {
                SHA1 sha1 = new SHA1CryptoServiceProvider();//创建SHA1对象
                byte[] bytes_in = encode.GetBytes(content);//将待加密字符串转为byte类型
                byte[] bytes_out = sha1.ComputeHash(bytes_in);//Hash运算
                sha1.Dispose();//释放当前实例使用的所有资源
                String result = BitConverter.ToString(bytes_out);//将运算结果转为string类型
                result = result.Replace("-", "").ToUpper();
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public T Deserialize<T>(string file_path)
        {
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Open)) //FileStream FileMode.Open
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(fs);
                }
            }
            catch
            {
                return default(T);
            }
        }

        public enum H_Level
        {
            None = 0,
            厂商 = 1,
            管理员 = 2,
            生产员 = 3,
            班组长 = 4,
        }

        private void Text_user_SelectedIndexChanged(object sender, EventArgs e)
        {
            Text_pass.Text = "";
        }
    }
}
